package com.shj.config.security;

import com.shj.entity.SysUser;
import com.shj.entity.SysUserRole;
import com.shj.service.SysUserRoleService;
import com.shj.service.SysUserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 *@Description spring security获取用户信息
 *@Author songhuajian
 *@Date 2020/1/10 14:59
 **/
@Component("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserRoleService sysUserRoleService;

    /**
     * @description 获取用户信息，存到user中
     * @author songhuajian
     * @date 2020/1/10 15:05
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findByUserId(username);
        if (sysUser == null){
            throw new UsernameNotFoundException("不存在该用户");
        }
        User user = new User(sysUser.getUserId(), sysUser.getPwd(), getAuthority(username));
        return user;
    }

    /**
     * @description 返回一个List集合,集合中装的是用户的角色信息
     * @author songhuajian
     * @date 2020/1/8 22:47
     */
    public List<SimpleGrantedAuthority> getAuthority(String username){
        List<SimpleGrantedAuthority> roleList = new ArrayList<>();
        //根据用户名查找角色信息
        List<SysUserRole> list = sysUserRoleService.findByUserId(username);
        for (int i=0;i<list.size();i++){
            SysUserRole sysUserRole = list.get(i);
            roleList.add(new SimpleGrantedAuthority(sysUserRole.getRoleId()));
        }
        return roleList;
    }
}
